package com.yanqu.road.server.manger;

import com.yanqu.road.entity.config.player.DecorationInfo;
import com.yanqu.road.entity.enums.eDecorationType;
import com.yanqu.road.entity.enums.eSexType;
import com.yanqu.road.entity.enums.eSpecialServerType;
import com.yanqu.road.logic.bussiness.config.DecorationBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class DecorationMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(DecorationMgr.class.getName());

    private static Map<Integer, Map<Integer, DecorationInfo>> decorationInfoTypeMap;

    private static Map<Integer, DecorationInfo> decorationInfoMap;

    private static Map<Integer, DecorationInfo> maleFreeDecorationMap;
    private static Map<Integer, DecorationInfo> femaleFreeDecorationMap;

    private static RandomHelper threadRandom = new RandomHelper();

    private static Map<Integer, List<DecorationInfo>> maleFreeDecorationListMap;
    private static Map<Integer, List<DecorationInfo>> femaleFreeDecorationListMap;

    public static final String SEPARATOR = "@#$";
    //使用分隔符时需要转义
    public static final String SPLIT_SEPARATOR = "@#\\$";

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean reloadConfig() {
        Map<Integer, Map<Integer, DecorationInfo>> dataTypeMap = new ConcurrentHashMap<>();
        Map<Integer, DecorationInfo> dataMap = new ConcurrentHashMap<>();
        DecorationBussiness.getDecorationInfoMap(dataTypeMap, dataMap);
        decorationInfoTypeMap = dataTypeMap;
        decorationInfoMap = dataMap;
        initFreeDecorationMap();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    private static void initFreeDecorationMap(){
        Map<Integer, DecorationInfo> maleDecorationMap = new ConcurrentHashMap<>();
        Map<Integer, DecorationInfo> femaleDecorationMap = new ConcurrentHashMap<>();
        Map<Integer, List<DecorationInfo>> maleDataMap = new ConcurrentHashMap<>();
        Map<Integer, List<DecorationInfo>> femaleDataMap = new ConcurrentHashMap<>();
        for(DecorationInfo decorationInfo : decorationInfoMap.values()){
            if(decorationInfo.isFree()){
                boolean addMale = false;
                boolean addFemale = false;
                if(eSexType.MALE.getValue() == decorationInfo.getSex()){
                    addMale = true;
                }else if(eSexType.FEMALE.getValue() == decorationInfo.getSex()){
                    addFemale = true;
                }else {
                    addMale = true;
                    addFemale = true;
                }
                if(addMale){
                    maleDecorationMap.put(decorationInfo.getId(), decorationInfo);
                    if(!maleDataMap.containsKey(decorationInfo.getType())){
                        maleDataMap.put(decorationInfo.getType(), new ArrayList<>());
                    }
                    maleDataMap.get(decorationInfo.getType()).add(decorationInfo);
                }
                if(addFemale){
                    femaleDecorationMap.put(decorationInfo.getId(), decorationInfo);
                    if(!femaleDataMap.containsKey(decorationInfo.getType())){
                        femaleDataMap.put(decorationInfo.getType(), new ArrayList<>());
                    }
                    femaleDataMap.get(decorationInfo.getType()).add(decorationInfo);
                }
            }
        }
        maleFreeDecorationMap = maleDecorationMap;
        femaleFreeDecorationMap = femaleDecorationMap;
        maleFreeDecorationListMap = maleDataMap;
        femaleFreeDecorationListMap = femaleDataMap;
    }

    public static Map<Integer, DecorationInfo> getDecorationInfoMap(int type){
        return decorationInfoTypeMap.get(type);
    }

    public static DecorationInfo getDecorationInfo(int decorationId){
        return decorationInfoMap.get(decorationId);
    }

    public static List<DecorationInfo> getMaleFreeDecorationList(){
        List<DecorationInfo> dataList = new ArrayList<>();
        boolean isIceServer = ConfigMgr.isTargetSpecialServer(eSpecialServerType.IceServer);
        // 不分性别
        for (DecorationInfo decorationInfo : maleFreeDecorationMap.values()) {
            if (!isIceServer) {//非寒冬特色服,不要生成寒冬的默认形象
                if(GameConfig.ICE_SERVER_PLAYER_DEC_KEY.contains(String.valueOf(decorationInfo.getId()))){
                    continue;
                }
            }
            dataList.add(decorationInfo);
        }
        return dataList;
    }

    public static List<DecorationInfo> getFemaleFreeDecorationList(){
        List<DecorationInfo> dataList = new ArrayList<>();
        boolean isIceServer = ConfigMgr.isTargetSpecialServer(eSpecialServerType.IceServer);
        // 不分性别
        for (DecorationInfo decorationInfo : femaleFreeDecorationMap.values()) {
            if (!isIceServer) {//非寒冬特色服,不要生成寒冬的默认形象
                if(GameConfig.ICE_SERVER_PLAYER_DEC_KEY.contains(String.valueOf(decorationInfo.getId()))){
                    continue;
                }
            }
            dataList.add(decorationInfo);
        }
        return dataList;
    }

    public static List<DecorationInfo> getMaleFreeDecorationList(int type){
        List<DecorationInfo> dataList = new ArrayList<>();
        List<DecorationInfo> decorationInfos = maleFreeDecorationListMap.get(type);
        if (decorationInfos == null) {
            return dataList;
        }
        boolean isIceServer = ConfigMgr.isTargetSpecialServer(eSpecialServerType.IceServer);
        for (DecorationInfo decorationInfo : decorationInfos) {
            if (!isIceServer) {//非寒冬特色服,不要生成寒冬的默认形象
                if(GameConfig.ICE_SERVER_PLAYER_DEC_KEY.contains(String.valueOf(decorationInfo.getId()))){
                    continue;
                }
            }
            dataList.add(decorationInfo);
        }
        return dataList;
    }

    public static List<DecorationInfo> getFemaleFreeDecorationList(int type){
        List<DecorationInfo> dataList = new ArrayList<>();
        List<DecorationInfo> decorationInfos = femaleFreeDecorationListMap.get(type);
        if (decorationInfos == null) {
            return dataList;
        }
        boolean isIceServer = ConfigMgr.isTargetSpecialServer(eSpecialServerType.IceServer);
        for (DecorationInfo decorationInfo : decorationInfos) {
            if (!isIceServer) {//非寒冬特色服,不要生成寒冬的默认形象
               if(GameConfig.ICE_SERVER_PLAYER_DEC_KEY.contains(String.valueOf(decorationInfo.getId()))){
                   continue;
               }
            }
            dataList.add(decorationInfo);
        }
        return dataList;
    }

    public static List<DecorationInfo> getFreeDecorationList(int sex){
        List<DecorationInfo> dataList = new ArrayList<>();
        // 不分性别
        dataList.addAll(getMaleFreeDecorationList());

        for (DecorationInfo decorationInfo : getFemaleFreeDecorationList()) {
            if (!dataList.contains(decorationInfo)) {
                dataList.add(decorationInfo);
            }
        }
        return dataList;
    }

    public static DecorationInfo getDefaultDecoration(int type, int sex){
        List<DecorationInfo> dataList;
        if(eSexType.MALE.getValue() == sex){
            dataList = getMaleFreeDecorationList(type);
        }else {
            dataList = getFemaleFreeDecorationList(type);
        }
        if(null != dataList && !dataList.isEmpty()){
            int randomIndex = threadRandom.next(0, dataList.size());
            return dataList.get(randomIndex);
        }
        return null;
    }

    public static int getDefaultDecorationId(int type, int sex){
        DecorationInfo decorationInfo = getDefaultDecoration(type, sex);
        if(null != decorationInfo){
            return decorationInfo.getId();
        }
        return 0;
    }

    /**
     * 拿默认服装
     */
    public static int getDefaultCostume(int sex, String decoration) {

        // 拿头（不是头像）（这个永远不变）
        List<Integer> decorationIdList = StringUtils.stringToIntegerList(decoration, DecorationMgr.SPLIT_SEPARATOR);
        int head = decorationIdList.get(3);

        // 拿免费配置
        List<DecorationInfo> headList;
        List<DecorationInfo> costumeList;
        if (eSexType.MALE.getValue() == sex) {
            headList = getMaleFreeDecorationList(eDecorationType.HeadIcon.getValue());
            costumeList = getMaleFreeDecorationList(eDecorationType.Costume.getValue());
        } else {
            headList = getFemaleFreeDecorationList(eDecorationType.HeadIcon.getValue());
            costumeList = getFemaleFreeDecorationList(eDecorationType.Costume.getValue());
        }

        // 【配置数量不同，走原来逻辑】
        if (headList.size() != costumeList.size()) {
            return getDefaultDecorationId(eDecorationType.Costume.getValue(), sex);
        }

        // 排个序（不改原来顺序）
        headList = headList.stream().sorted(Comparator.comparing(DecorationInfo::getId)).collect(Collectors.toList());
        costumeList = costumeList.stream().sorted(Comparator.comparing(DecorationInfo::getId)).collect(Collectors.toList());

        // 按下标找
        for (int i = 0; i < headList.size(); i++) {
            if (headList.get(i).getId() == head) {
                return costumeList.get(i).getId();
            }
        }

        // 走原来逻辑
        return getDefaultDecorationId(eDecorationType.Costume.getValue(), sex);
    }

    /**
     * 获取默认装饰
     */
    public static String getDefaultDecoration(int sex){
        String decoration = "";
        int decorationId = getDefaultDecorationId(eDecorationType.HeadIcon.getValue(), sex);
        if(0 == decorationId){
            return decoration;
        }
        int headId = decorationId;
        decoration = decorationId + SEPARATOR;
        decorationId = getDefaultDecorationId(eDecorationType.HeadFrame.getValue(), sex);
        decoration = decoration + decorationId + SEPARATOR;
        decorationId = getDefaultDecorationId(eDecorationType.HonoraryTitle.getValue(), sex);
        decoration = decoration + decorationId + SEPARATOR;
        decoration = decoration + headId + SEPARATOR;
        decorationId = getDefaultDecorationId(eDecorationType.Costume.getValue(), sex);
        decoration = decoration + decorationId + SEPARATOR;
        //加聊天气泡
        return decoration + getDefaultDecorationId(eDecorationType.ChatBubble.getValue(), sex);
    }

    /**
     * web填充玩家装饰
     */
    public static String webFullDefaultDecoration(int headId, int costumeId, int sex){
        String decoration = headId + SEPARATOR;
        int decorationId = getDefaultDecorationId(eDecorationType.HeadFrame.getValue(), sex);
        decoration = decoration + decorationId + SEPARATOR;
        decorationId = getDefaultDecorationId(eDecorationType.HonoraryTitle.getValue(), sex);
        decoration = decoration + decorationId + SEPARATOR;
        // 加 头部形象
        decoration = decoration + headId + SEPARATOR;
        // 加 身体形象
        decoration = decoration + costumeId + SEPARATOR;
        //聊天气泡
        decoration = decoration + getDefaultDecorationId(eDecorationType.ChatBubble.getValue(), sex);
        return decoration;
    }

    /**
     * 修正玩家装饰数据
     * @param decorationList
     */
    public static boolean fixDecoration(List<String> decorationList, int sex) {
        boolean change = false;
        int size = decorationList.size();
        String defaultDecoration = getDefaultDecoration(sex);
        List<Integer> defaultList = StringUtils.stringToIntegerList(defaultDecoration, SPLIT_SEPARATOR);
        for (int i = size; i < defaultList.size(); i++) {
            decorationList.add(String.valueOf(defaultList.get(i)));
            change = true;
        }
        return change;

    }
}
